package MVC;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import protocol.ChatMessage;
import protocol.FileNotify;

public class ChatGui extends javax.swing.JFrame implements Runnable {

    private ChatController mon_controller;
    private ChatModel mon_model;
    // Mémorisation de la comic action choisie par l'utilisateur
    private int selectedComicAction = 0;

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jListUser = new javax.swing.JList();
        buttonSend = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        textToSend = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        textRcd = new javax.swing.JTextArea();
        jconnect = new javax.swing.JButton();
        jdisconnect = new javax.swing.JButton();
        jusername = new javax.swing.JTextField();
        jSendFile = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jListUser.setModel(mon_controller.getdlm());
        //   String[] strings = {};
        // public int getSize() { return strings.length; }
        //  public Object getElementAt(int i) { return strings[i]; }
        //});
jScrollPane2.setViewportView(jListUser);

buttonSend.setText("Send");
buttonSend.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        buttonSendMouseClicked(evt);
    }
    });
    buttonSend.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            buttonSendActionPerformed(evt);
        }
    });

    textToSend.setColumns(25);
    textToSend.setRows(5);
    jScrollPane1.setViewportView(textToSend);

    textRcd.setColumns(20);
    textRcd.setRows(5);
    jScrollPane3.setViewportView(textRcd);

    jconnect.setText("Connect");
    jconnect.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jconnectMouseClicked(evt);
        }
    });

    jdisconnect.setText("Disconnect");
    jdisconnect.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jdisconnectMouseClicked(evt);
        }
    });

    jusername.setText("Choose an username !");

    jSendFile.setText("Send File");
    jSendFile.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jSendFileMouseClicked(evt);
        }
    });

    jProgressBar1.setMinimum(0);
    jProgressBar1.setMaximum(100);

    jButton1.setText("Comic actions");
    jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jButton1MouseClicked(evt);
        }
    });

    jButton2.setText("Nasty Actions");
    jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jButton2MouseClicked(evt);
        }
    });

    jButton3.setText("About");
    jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jButton3MouseClicked(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jdisconnect, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jconnect, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(12, 12, 12)
                            .addComponent(jusername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
                        .addComponent(jButton3)))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addComponent(jSendFile, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE)
                    .addGap(32, 32, 32)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jButton2)
                    .addGap(4, 4, 4)
                    .addComponent(jButton1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(buttonSend, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jusername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton3))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jconnect)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jdisconnect)
                    .addGap(18, 18, 18)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE)))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jSendFile)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSend, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE))
            .addContainerGap())
    );

    pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSendActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_buttonSendActionPerformed

    private void buttonSendMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buttonSendMouseClicked

        if (jListUser.getSelectedValue() == null) {
            BasicPrompt prompt_erreur = new BasicPrompt("Aucun utilisateur sélectionné !");
            prompt_erreur.setVisible(true);
        } else {


            try {
                System.out.println(mon_model.getMon_username());
                ChatMessage m1 = new ChatMessage(mon_model.getMon_username(), textToSend.getText(), InetAddress.getLocalHost());
                mon_controller.send((String) jListUser.getSelectedValue(), m1);
                //vider ce qu'il y a dans la partie du send
                textToSend.setText("");
            } catch (UnknownHostException ex) {
                System.out.println("Probleme dans le bouton envoi !");
            }


    }//GEN-LAST:event_buttonSendMouseClicked
    }
    private void jconnectMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jconnectMouseClicked
        try {
            mon_controller.connexion(jusername.getText());
            jdisconnect.setEnabled(true);
            buttonSend.setEnabled(true);
            textToSend.setEnabled(true);
            jconnect.setEnabled(false);
            jusername.setEnabled(false);
            jSendFile.setEnabled(true);
        } catch (UnknownHostException ex) {
            System.out.println("Erreur lors de la connexion");
        }

    }//GEN-LAST:event_jconnectMouseClicked

    private void jdisconnectMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jdisconnectMouseClicked
        try {
            mon_controller.deconnexion(jusername.getText());
            jdisconnect.setEnabled(false);
            buttonSend.setEnabled(false);
            textToSend.setEnabled(false);
            jconnect.setEnabled(true);
            jusername.setEnabled(true);
            jSendFile.setEnabled(false);
        } catch (UnknownHostException ex) {
            System.out.println("Erreur lors de la comon_model.getUnnexion");
        }
    }//GEN-LAST:event_jdisconnectMouseClicked

    private void jSendFileMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jSendFileMouseClicked

        // Si aucun utilisateur n'est selectionne
        // On affiche un prompt d'erreur !
        if (jListUser.getSelectedValue() == null) {
            BasicPrompt prompt_erreur = new BasicPrompt("Aucun utilisateur sélectionné !");
            prompt_erreur.setVisible(true);
        } else {


            // Création d'une fenêtre de choix du fichier
            JFileChooser choix = new JFileChooser();
            int retour = choix.showOpenDialog(null);

            // Si un fichier est sélectionné puis qu'on appuie sur "ok"
            if (retour == JFileChooser.APPROVE_OPTION) {
                File f = choix.getSelectedFile();
                FileNotify fn;
                try {
                    // On envoie une notification à l'hote distant
                    fn = new FileNotify(mon_model.getMon_username(), InetAddress.getLocalHost(), f.getName());

                    // Et on mémorise les informations sur ce fichier dans notre objet de classe SendTCP
                    mon_controller.send((String) jListUser.getSelectedValue(), fn);
                    mon_controller.setFileSentInformation(f.getName(), f.getAbsolutePath());
                } catch (UnknownHostException ex) {
                    System.out.println("Probleme lors de l'envoi du FileNotify !");
                }
            }
        }
    }//GEN-LAST:event_jSendFileMouseClicked

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
// TODO add your handling code here:

    if (jListUser.getSelectedValue() == null) {
        BasicPrompt prompt_erreur = new BasicPrompt("Aucun utilisateur sélectionné !");
        prompt_erreur.setVisible(true);
    } else {

        ComicActions mon_ca = new ComicActions(this, mon_controller, mon_model);
        mon_ca.setVisible(true);
        String distant_user = (String) jListUser.getSelectedValue();
        String mon_string = null;
        ChatMessage mon_message = null;
        // Tant que l'utilisateur n'a pas cliqué sur un bouton on attend
        // On crée et on envoie un message lié au bouton sur lequel l'utilisateur a appuyé
    }
}//GEN-LAST:event_jButton1MouseClicked

private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
    BasicPrompt mon_prompt = new BasicPrompt("En raison du mauvais caractère des étudiants du groupe 4IR-A1, ces fonctions ont été désactivées. ;)");
    mon_prompt.setVisible(true);
}//GEN-LAST:event_jButton2MouseClicked

private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked
    About mon_prompt = new About();
    mon_prompt.setVisible(true);
}//GEN-LAST:event_jButton3MouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonSend;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JList jListUser;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton jSendFile;
    private javax.swing.JButton jconnect;
    private javax.swing.JButton jdisconnect;
    private javax.swing.JTextField jusername;
    private javax.swing.JTextArea textRcd;
    private javax.swing.JTextArea textToSend;
    // End of variables declaration//GEN-END:variables

    /** Creates new form ChatGui */
    public ChatGui() {
    }

    protected void setController(ChatController c) {
        this.mon_controller = c;
        initComponents();
    }

    protected void setModel(ChatModel cm) {
        this.mon_model = cm;
    }

    public void run() {
        this.setVisible(true);
        jdisconnect.setEnabled(false);
        buttonSend.setEnabled(false);
        textToSend.setEnabled(false);
        jSendFile.setEnabled(false);
    }

    public void setZoneTexte(String s) {
        textRcd.append(s);
    }

    public void progressbarEnable() {
        this.jProgressBar1.setVisible(true);
    }

    public void progressbarDisable() {
        this.jProgressBar1.setVisible(false);
    }

    public void progressbarUpdate(int progress) {
        this.jProgressBar1.setStringPainted(true);
        this.jProgressBar1.setValue(progress);
        this.jProgressBar1.setString(progress + " %");
    }

    public void progressbartext(String text) {
        this.jProgressBar1.setString(text);
    }

    public void setAnswer(int Anwser) {
        this.selectedComicAction = Anwser;
    }

    public int getAnswer() {
        return this.selectedComicAction;
    }

    public Object getSelectedValue() {
        return this.jListUser.getSelectedValue();
    }
}
